<template>
  <van-search
    v-model="value"
    show-action
    shape="round"
    placeholder="请输入搜索关键词"
    @search="onSearch"
    @keyup.enter="onSearch"
  >
    <template #left>
      <div><van-icon name="arrow-left" color="blue" @click="onGoBack" /></div>
    </template>
    <template #action>
      <div @click="onSearch">搜索</div>
    </template>
  </van-search>

  <div class="search-history-del">
    <span>搜索历史</span><van-icon name="delete-o" @click="removeAll" />
  </div>
  <div v-for="item in searchHistory" class="historyOne">
    <p @click="goSearch(item)">{{ item }}</p>
    <van-icon
      name="cross"
      size="5"
      style="position: absolute; top: -8px; right: -8px"
      @click="removeVal(item)"
    />
  </div>
</template>

<script>
export default {
  name: "Search",
  data() {
    return {
      value: "",
      searchHistory: localStorage.getItem("searchHistory")
        ? JSON.parse(localStorage.getItem("searchHistory"))
        : [],
    };
  },
  methods: {
    onGoBack() {
      this.$router.back(-1);
    },
    onSearch() {
      if (this.value == "") return;
      let searchHistory = localStorage.getItem("searchHistory");
      if (!searchHistory) {
        searchHistory = [];
      } else {
        searchHistory = JSON.parse(searchHistory);
      }
      const index = searchHistory.indexOf(this.value);
      if (index != -1) {
        searchHistory.splice(index, 1);
      }
      searchHistory.unshift(this.value);
      localStorage.setItem("searchHistory", JSON.stringify(searchHistory));
      // this.goSearch(this.value);
      this.searchHistory = searchHistory;
      this.goSearch(this.value);
      this.value = "";
    },
    // 删除单个历史记录
    removeVal(v) {
      this.searchHistory = this.searchHistory.filter((item) => item != v);
      localStorage.setItem("searchHistory", JSON.stringify(this.searchHistory));
    },
    // 删除全部历史记录
    removeAll() {
      localStorage.removeItem("searchHistory");
      this.searchHistory = [];
    },
    goSearch(item) {
      this.$router.push({
        path: "/SearchGoods",
        query: {
          key: item,
        },
      });
    },
  },
};
</script>

<style scoped>
.search-history-del {
  width: 100%;
  display: flex;
  padding: 0.2rem;
  align-items: center;
  justify-content: space-between;
}
.search-history {
  display: inline-block;
  min-width: 0.2rem;
  min-height: 0.2rem;
  background-color: #ededed;
  padding: 0.1rem;
  margin: 0.1rem;
  text-align: center;
  border: 2px solid #ccc;
  border-radius: 0.1rem;
  font-size: 0.14rem;
}
.historyOne {
  position: relative;
  display: inline-block;
  min-width: 0.2rem;
  background-color: rgb(214, 212, 212);
  color: #000;
  border-radius: 0.04rem;
  padding: 5px;
  margin: 5px 10px;
}
</style>
